#include "sessionfriendarea.h"
#include "debug.h"
#include "mainwidget.h"
#include "./model/datacenter.h"

///////////////////////////////
// 滚动区域
///////////////////////////////
SessionFriendArea::SessionFriendArea(QScrollArea *parent)
    : QScrollArea{parent}
{
    this->setWidgetResizable(true);
    // 设置滚动条样式
    this->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px; background-color: rgb(46, 46, 46); }");
    this->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px; }");
    // this->setStyleSheet("QScrollArea { background-color: rgb(46, 46, 46); }");

    // 创建出widget
    _container = new QWidget();
    _container->setFixedWidth(this->width());
    // container->setStyleSheet("QWidget { background-color: rgb(46, 46, 46); }");
    this->setWidget(_container);

    // 给container设置布局管理器
    QVBoxLayout *layout = new QVBoxLayout();
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    layout->setAlignment(Qt::AlignTop);
    _container->setLayout(layout);

    // 简单测试滚动效果
    // for (int i = 0; i < 50; i++)
    // {
    //     QLabel *label = new QLabel();
    //     label->setText("test");
    //     layout->addWidget(label);
    // }

#if TEST_UI
    for (int i = 0; i < 20; i++)
    {
        addItem(Session, QString::number(i), QIcon(":/resource/image/defaultAvatar.png"), "张三" + QString::number(i), "消息" + QString::number(i));
    }
#endif
}

void SessionFriendArea::clear()
{
    QLayout *layout = _container->layout();
    // 遍历布局管理器中的所有元素, 并且删除
    int i = layout->count() - 1;
    while (i >= 0)
    {
        QLayoutItem *item = layout->takeAt(i);
        if (item->widget())
            delete item->widget();
        i--;
    }
}

void SessionFriendArea::addItem(ItemType itemType, const QString &id, const QIcon &avatar, const QString &name, const QString &text)
{
    SessionFriendItem *item = nullptr;

    if (itemType == Session)
        item = new SessionItem(this, id, avatar, name, text);
    else if (itemType == Friend)
        item = new FriendItem(this, id, avatar, name, text);
    else if (itemType == Apply)
        item = new ApplyItem(this, id, avatar, name);
    else
    {
        ERROR() << "item类型错误";
        return;
    }

    if (item)
        _container->layout()->addWidget(item);
}

void SessionFriendArea::clickItem(int index)
{
    if (index < 0 || index >= _container->layout()->count())
    {
        ERROR() << "点击元素的下标超出范围: index=" << index;
        return;
    }
    QLayoutItem *layoutItem = _container->layout()->itemAt(index);
    if (layoutItem == nullptr || layoutItem->widget() == nullptr)
    {
        ERROR() << "指定元素不存在: index=" << index;
        return;
    }
    SessionFriendItem *item = dynamic_cast<SessionFriendItem*>(layoutItem->widget());
    item->select();
}

///////////////////////////////
// 滚动区域中的item
///////////////////////////////
SessionFriendItem::SessionFriendItem(QWidget *owner, const QIcon &avatar, const QString &name, const QString &msg)
    :_owner(owner)
{
    this->setFixedHeight(70);
    this->setStyleSheet("QWidget { background-color: rgb(231, 231, 231); }");
    
    // 网格布局管理器
    QGridLayout *layout = new QGridLayout();
    layout->setContentsMargins(5, 0, 0, 0);
    layout->setHorizontalSpacing(10);
    layout->setVerticalSpacing(0);
    this->setLayout(layout);
    
    // 创建头像
    _avatarBtn = new QPushButton();
    _avatarBtn->setFixedSize(QSize(50, 50));
    _avatarBtn->setIconSize(QSize(50, 50));
    _avatarBtn->setIcon(avatar);
    _avatarBtn->setStyleSheet("QPushButton { border: none; }");
    _avatarBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    
    // 创建昵称
    _nameLabel = new QLabel();
    _nameLabel->setFixedHeight(35);
    _nameLabel->setStyleSheet("QLabel { font-size: 16px; font-weight: 600; }");
    _nameLabel->setText(name);
    _nameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 消息预览
    _textLabel = new QLabel();
    _textLabel->setFixedHeight(35);
    _textLabel->setText(msg);
    _textLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    layout->addWidget(_avatarBtn, 0, 0, 2, 1); // 第0行, 第0列, 跨2行, 跨2列
    layout->addWidget(_nameLabel, 0, 1, 1, 12);
    layout->addWidget(_textLabel, 1, 1, 1, 12);
}

void SessionFriendItem::paintEvent(QPaintEvent *ev)
{
    (void)ev;
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

void SessionFriendItem::mousePressEvent(QMouseEvent *ev)
{
    (void)ev;
    select();
}

void SessionFriendItem::enterEvent(QEnterEvent *ev)
{
    (void)ev;
    if (_select) return;
    this->setStyleSheet("QWidget { background-color: rgb(215, 215, 215); }");
}

void SessionFriendItem::leaveEvent(QEvent *ev)
{
    (void)ev;
    if (_select) return;
    this->setStyleSheet("QWidget { background-color: rgb(231, 231, 231); }");
}

void SessionFriendItem::select()
{
    // 将之前被选中的还原
    const QObjectList chilren = this->parentWidget()->children();
    for (QObject *child : chilren)
    {
        if (!child->isWidgetType())
            continue;
        SessionFriendItem *item = dynamic_cast<SessionFriendItem*>(child);
        if (item->_select)
        {
            item->_select = false;
            item->setStyleSheet("QWidget { background-color: rgb(231, 231, 231); }");
        }
    }

    // 点击时设置更深的背景颜色
    this->setStyleSheet("QWidget { background-color: rgb(205, 205, 205); }");
    _select = true;

    active();
}

///////////////////////////////
// 会话item
///////////////////////////////
SessionItem::SessionItem(QWidget *owner, const QString &chatSessionId, const QIcon &avatar, const QString &name, const QString &msg)
    :SessionFriendItem(owner, avatar, name, msg), _chatSessionId(chatSessionId), _msg(msg)
{
    model::DataCenter *dataCenter = model::DataCenter::getInstance();
    connect(dataCenter, &model::DataCenter::updateLastMsg, this, &SessionItem::updateLastMsg);

    int unread = dataCenter->getUnread(_chatSessionId);
    if (unread > 0)
        _textLabel->setText(QString("[未读%1条] ").arg(unread) + _msg);
}

void SessionItem::active()
{
    // 加载历史消息
    MainWidget *mainWidget = MainWidget::getInstance();
    mainWidget->loadRecentMessage(_chatSessionId);

    model::DataCenter *dataCenter = model::DataCenter::getInstance();
    dataCenter->clearUnread(_chatSessionId);
    _textLabel->setText(_msg);
}

void SessionItem::updateLastMsg(const QString &chatSessionId)
{
    model::DataCenter *dataCenter = model::DataCenter::getInstance();
    if (_chatSessionId != chatSessionId)
        return;
    QList<MessageInfo> *msgList = dataCenter->getRecentMsg(chatSessionId);
    if (msgList == nullptr) return;
    const MessageInfo &msgInfo = msgList->back();

    if (msgInfo._message_type == model::MessageType::STRING_TYPE)
        _msg = msgInfo._content;
    else if (msgInfo._message_type == model::MessageType::IMAGE_TYPE)
        _msg = "[图片]";
    else if (msgInfo._message_type == model::MessageType::FILE_TYPE)
        _msg = "[文件]";
    else if (msgInfo._message_type == model::MessageType::SPEECH_TYPE)
        _msg = "[语音]";
    else
    {
        ERROR() << "消息类型错误 type: " << msgInfo._message_type;
        return;
    }
    _textLabel->setText(_msg);
    if (dataCenter->getCurrentSessionId() != _chatSessionId)
    {
        int unread = dataCenter->getUnread(_chatSessionId);
        if (unread > 0)
            _textLabel->setText(QString("[未读%1条] ").arg(unread) + _msg);
    }
    dataCenter->updateChatSessionLastMsg(chatSessionId, msgInfo);
}

///////////////////////////////
// 好友item
///////////////////////////////
FriendItem::FriendItem(QWidget *owner, const QString &friendId, const QIcon &avatar, const QString &name, const QString &desc)
    :SessionFriendItem(owner, avatar, name, desc), _friendId(friendId){}

void FriendItem::active()
{
    // 跳转到相应会话
    MainWidget *mainWidget = MainWidget::getInstance();
    mainWidget->switchToSession(_friendId);
}

///////////////////////////////
// 申请item
///////////////////////////////
ApplyItem::ApplyItem(QWidget *owner, const QString &userId, const QIcon &avatar, const QString &name)
    :SessionFriendItem(owner, avatar, name, ""), _userId(userId)
{
    // 移除父类msgLabel
    QGridLayout *layout = dynamic_cast<QGridLayout*>(this->layout());
    layout->removeWidget(_textLabel);
    delete _textLabel;

    // 添加两个按钮
    _acceptBtn = new QPushButton();
    _acceptBtn->setText("同意");
    _rejectBtn = new QPushButton();
    _rejectBtn->setText("拒绝");

    layout->addWidget(_acceptBtn, 1, 1, 1, 1);
    layout->addWidget(_rejectBtn, 1, 2, 1, 1);
}

void ApplyItem::mousePressEvent(QMouseEvent *ev){}

void ApplyItem::active()
{

}
